package cn.ac.cintcm.dao.hibernate;

import java.util.List;

import javax.persistence.Table;

import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import cn.ac.cintcm.dao.UserDao;
import cn.ac.cintcm.model.User;

public abstract class UserDaoGeneric extends GenericDaoHibernate<User, Long> implements UserDao, UserDetailsService {

    /**
     * Constructor that sets the entity to User.class.
     */
    public UserDaoGeneric() {
        super(User.class);
    }

	/**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        return getHibernateTemplate().find("from User u order by u.username");
    }

    /**
     * {@inheritDoc}
     */
    public User saveUser(User user) {
        log.debug("user's id: " + user.getId());
        getHibernateTemplate().saveOrUpdate(user);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return user;
    }

    /**
     * Overridden simply to call the saveUser method. This is happenening 
     * because saveUser flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public User save(User user) {
        return this.saveUser(user);
    }

    /** 
     * {@inheritDoc}
    */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List users = getHibernateTemplate().find("from User where username=?", username);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
    }

    /** 
     * {@inheritDoc}
    */
    public String getUserPassword(String username) {
        SimpleJdbcTemplate jdbcTemplate =
                new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
        Table table = AnnotationUtils.findAnnotation(User.class, Table.class);
        return jdbcTemplate.queryForObject(
                "select password from " + table.name() + " where username=?", String.class, username);

    }


	public String getUserPassword(Long id) {
        SimpleJdbcTemplate jdbcTemplate =
            new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
	    Table table = AnnotationUtils.findAnnotation(User.class, Table.class);
	    return jdbcTemplate.queryForObject(
	            "select password from " + table.name() + " where id=?", String.class, id);

	}
	
	public User get(String userName) {
        List users = getHibernateTemplate().find("from User where username=?", userName);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + userName + "' not found...");
        } else {
            return  (User) users.get(0);
        }
	}

	@SuppressWarnings("unchecked")
	public List<User> search(String key) {
		String hsql = "select u from User u where u.username like '%" + key + "%' or name like '%" 
			+ key + "%' or relative like '%" + key +"%' or memo like '%" + key +"%'";
		return getHibernateTemplate().find(hsql);
	}

	@SuppressWarnings("unchecked")
	public List<User> search(String key, Long userId) {
		String hsql = "select p from User d join d.patients p where (p.username like '%" + key + "%' or p.name like '%" 
			+ key + "%' or p.relative like '%" + key + "%' or p.memo like '%" + key +"%') and d.id=" + userId;
		log.debug(hsql);
		return getHibernateTemplate().find(hsql);
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getDoctors() {
		List<User> users = getHibernateTemplate().find("from User u where u.isDoctor=1 and u.enabled=1");
		return users;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getPatiens(Long id) {
		List<User> users = getHibernateTemplate().find("select p from User d join d.patients p where d.id=?", id);
		return users;
	}
	
	public List<User> getNewDoctors() {
		List<User> users = getHibernateTemplate().find("from User u where u.isDoctor=1 and u.enabled=0");
		return users;		
	}
}
